package com.example.communitypro.service.impl;

import com.example.communitypro.mapper.*;
import com.example.communitypro.pojo.*;
import com.example.communitypro.service.NotificationService;
import com.example.communitypro.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NotificationServiceImpl implements NotificationService {
    @Autowired(required = false)
    private NotificationMapper notificationMapper;
    @Autowired(required = false)
    private UserDetailsMapper userDetailsMapper;
    @Autowired(required = false)
    private PostMapper postMapper;
    @Autowired(required = false)
    private CommentMapper commentMapper;

    @Autowired(required = false)
    private CommunityInformationMapper communityInformationMapper;
    /**
     *
     * @param record 里面有post_no属性，并非一定代表贴子no
     * @return
     */
    @Override
    public Result addNotification(Notification record) {
        int userNo = record.getUserNo();
        int type = record.getNotificationType();

        List<Notification> notifications = notificationMapper.queryNotificationByuserNoAndPostNo(userNo, record.getPostNo());
        for (Notification notification : notifications) {
            notificationMapper.updateIsReadByUserNo(notification.getNotificationId(), 1);
        }

        //为了获取用户名
        UserDetails userDetails = userDetailsMapper.selectByUser(userNo);

        //为了获取贴子标题
        Post post = null;

        Comment comment = null;

        if (type==3){
            comment = commentMapper.selectByPrimaryKey(record.getPostNo());
            //为后续评论的评论准备
            post = postMapper.selectByPrimaryKey(comment.getPostNo());
        }else if(type==4){
            comment = commentMapper.selectByPrimaryKey(record.getPostNo());
            //为后续评论的评论准备
            post = postMapper.selectByPrimaryKey(comment.getPostNo());
        }else {
            post = postMapper.selectByPrimaryKey(record.getPostNo());
        }
        //刚开始默认设置为未读
        record.setNotificationIsread(0);

        String context = "";
        //0：被关注；1：点赞贴子；2：收藏；3：点赞评论 ；4：收藏评论 5:评论贴子

        try {
            if (type == 0){
                context = userDetails.getUserName()+"---关注了你";
            }else if(type==1){
                context = userDetails.getUserName()+"对标题为---"+post.getPostTitle()+"---的贴子点赞啦";
            }else if(type==2){
                context = userDetails.getUserName()+"收藏了标题为---"+post.getPostTitle()+"---的贴子";
            }else if (type==3){
                context = userDetails.getUserName()+"---点赞了内容为---"+comment.getCommentContent()+"---的评论";
            }else if(type==4){
                context = userDetails.getUserName()+"---收藏了你的评论---"+comment.getCommentContent();
            }else if (type==5){
                context = userDetails.getUserName()+"---评论了标题为---"+post.getPostTitle()+"---的贴子";
            }else if (type==6){
                context = userDetails.getUserName()+"---发布了标题为---"+post.getPostTitle()+"---的贴子";
            }
            record.setNotificationContext(context);

            if(notificationMapper.insertSelective(record)>0) {
                return Result.ok().message("新增通知成功");
            }else {
                return Result.error().message("新增通知失败"); 
            }
        }catch (Exception e){
            System.out.println("类型错误，不影响程序。。。");
            return Result.error().message("新增通知失败");
        }
    }

    public Result addNotificationPro(Notification record,String postTitle){
        int userNo = record.getUserNo();
        int type = record.getNotificationType();

        try {
            CommunityInformation communityInformation = communityInformationMapper.selectByPrimaryKey(record.getPostNo());

            //为了获取用户名
            UserDetails userDetails = userDetailsMapper.selectByUser(userNo);
            Post post = postMapper.selectByPrimaryKey(record.getPostNo());
            String context = userDetails.getUserName()+"---发布了标题为---"+postTitle+"---的贴子，所属社区["+communityInformation.getCommunityName()+"]";
            record.setNotificationContext(context);
            record.setNotificationIsread(0);
            if(notificationMapper.insertSelective(record)>0) {
                return Result.ok().message("新增通知成功");
            }else {
                return Result.error().message("新增通知失败");
            }
        }catch (Exception e){
            System.out.println("错了，不管了！");
            return Result.error().message("新增通知失败");
        }
    }

    @Override
    public List<Notification> queryNotificationByType(Integer type) {
        return notificationMapper.queryNotificationByType(type);
    }

    @Override
    public Result dropNotification(int notification_id) {
        try {
            if(notificationMapper.deleteByPrimaryKey(notification_id)>0) {
                return Result.ok().message("删除通知成功");
            }else {
                return Result.error().message("删除通知失败");
            }
        }catch (Exception e) {
            return Result.error().message("删除通知错误");
        }
    }

    @Override
    public Result modifyNotification(Notification record) {
        try {
            if(notificationMapper.updateByPrimaryKeySelective(record)>0) {
                return Result.ok().message("修改成功");
            }else {
                return Result.error().message("修改失败：未找到对应记录");
            }
        }catch (DuplicateKeyException e) {
            System.err.println(e);
            return Result.error().message("修改错误：已经存在对应记录");
        }
        catch (Exception e) {
            System.err.println(e);
            return Result.error().message("修改错误："+e.toString());
        }
    }

    @Override
    public Result queryNotification(int notification_id) {
        try {
            Notification notification = notificationMapper.selectByPrimaryKey(notification_id);
            if(notification!=null) {
                return Result.ok().message("查询成功").data("notification",notification).count(1);
            }else {
                return Result.error().message("查询失败");
            }
        }catch (Exception e) {
            return Result.error().message("查询错误");
        }
    }

    @Override
    public Result selectAll() {
        List<Notification> notificationList = notificationMapper.selectAll();
        try {
            if(notificationList!=null) {
                return Result.ok().message("查询成功").count(notificationList.size());
            }else {
                return Result.error().message("查询失败");
            }
        }catch (Exception e) {
            return Result.error().message("查询错误");
        }
    }

    @Override
    public Result queryNotificationByUserNo(Integer userNo) {
        List<Notification> notificationList = notificationMapper.queryNotificationByUserNo(userNo);

        try {
            Result result = Result.ok().message("查询成功").data("notifications", notificationList);
            if(notificationList!=null) {
                for (Notification notification : notificationList) {
                    UserDetails userDetails = userDetailsMapper.selectByUser(notification.getUserNo());
                    notification.setUserData(userDetails);

                    if (notification.getNotificationType() == 0){
                        UserDetails own = userDetailsMapper.selectByUser(notification.getPostNo());
                        notification.setContextData(own);
                    }else if (notification.getNotificationType() == 1 || notification.getNotificationType() == 2 || notification.getNotificationType() == 5|| notification.getNotificationType() == 6){
                        Post post = postMapper.selectByPrimaryKey(notification.getPostNo());
                        notification.setContextData(post);
                    }/*else if (){
                        Post post = postMapper.selectByPrimaryKey(notification.getPostNo());
                        notification.setContextData(post);
                    }*/
                    else if (notification.getNotificationType() == 3 || notification.getNotificationType() == 4){
                        Comment comment = commentMapper.selectByPrimaryKey(notification.getPostNo());
                        notification.setContextData(comment);
                    }/*else if(){

                    }*/

                }
                return result;

            }else {
                return Result.error().message("查询失败");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("查询错误");
        }
    }

    @Override
    public Result updateIsReadByUserNo(Integer notificationId) {

        //按照正常逻辑只能从未读到已读
        int isRead = 1;

        try {
            if(notificationMapper.updateIsReadByUserNo(notificationId,isRead)>0) {
                return Result.ok().message("修改成功");
            }else {
                return Result.error().message("修改失败：未找到对应记录");
            }
        } catch (Exception e) {
            System.err.println(e);
            return Result.error().message("修改错误："+e.toString());
        }
    }


}
